<template>
  <div>
    <v-data-table
      class="items-table"
      :headers="tableHeaders"
      :items="propItems"
      disable-sort
      hide-default-footer
    >
      <template #item="{ item, isExpanded, expand }">
        <tr
          @click="expand(!isExpanded)"
          class="text-left pointer v-row-group__header"
        >
          <td class="pointer px-0" colspan="1">
            <v-icon v-if="!isExpanded"> mdi-chevron-up </v-icon>
            <v-icon v-else> mdi-chevron-down </v-icon>{{ item.line }}
          </td>
          <td class="pointer" colspan="1">
            <v-card
              class="d-flex align-center justify-space-between"
              :class="{ 'no-content rounded-1': !item.description }"
              width="100%"
              height="100%"
              flat
              color="transparent"
            >
              <v-edit-dialog :return-value.sync="item.description">
                <div class="text">
                  {{ item.description }}
                </div>
                <template v-slot:input>
                  <v-text-field v-model="item.description"></v-text-field>
                </template>
              </v-edit-dialog>
              <v-tooltip bottom>
                <template v-slot:activator="{ on }">
                  <v-icon
                    @click.stop="addItem(item)"
                    v-on="on"
                    class="float-right ml-2"
                    color="#79839B"
                  >
                    mdi-plus-thick
                  </v-icon>
                </template>
                <span>Add Item</span>
              </v-tooltip>
            </v-card>
          </td>
          <td class="pointer" colspan="4"></td>
          <td class="pointer" colspan="1">
            {{ arrObjSum(item.children, "totalCost") }}
          </td>
          <td class="pointer" colspan="1">
            {{ arrObjSum(item.children, "totalAmt") }}
          </td>
          <td class="pointer" colspan="1">
            {{ arrObjSum(item.children, "gain") }}
          </td>
          <td class="pointer" colspan="1">
            {{ arrObjAverage(item.children, "gp") }}
          </td>
          <td class="pointer" colspan="1"></td>
        </tr>
      </template>
      <template v-slot:expanded-item="{ headers, item }">
        <tr v-for="child in item.children" :key="child.id">
          <td
            v-for="header in headers"
            :key="header.value"
            class="text-left"
            :class="{ 'pl-6': header.value === 'line' }"
            :colspan="1"
          >
            <template v-if="header.value === 'line'">
              {{ child.line }}
            </template>
            <template v-else-if="header.value === 'description'">
              <v-card
                flat
                height="100%"
                color="transparent"
                class="d-flex align-center justify-space-between"
                :class="{ 'no-content rounded-1': !child.description }"
              >
                <v-edit-dialog :return-value.sync="child.description">
                  <div class="text">
                    {{ child.description }}
                  </div>
                  <template v-slot:input>
                    <v-text-field v-model="child.description"></v-text-field>
                  </template>
                </v-edit-dialog>
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-icon
                      @click="openSelectItem(child)"
                      v-on="on"
                      class="ml-2 bold-icon pointer float-right"
                      color="#79839B"
                    >
                      mdi-magnify
                    </v-icon>
                  </template>
                  <span>Select Item</span>
                </v-tooltip>
              </v-card>
            </template>
            <template v-else-if="header.value === 'supplier'">
              <v-card
                flat
                height="100%"
                color="transparent"
                class="d-flex align-center justify-space-between"
                :class="{ 'no-content rounded-1': !child.supplier }"
              >
                <v-edit-dialog :return-value.sync="child.supplier">
                  <div class="text">
                    {{ child.supplier }}
                  </div>
                  <template v-slot:input>
                    <v-text-field v-model="child.supplier"></v-text-field>
                  </template>
                </v-edit-dialog>
                <v-tooltip bottom>
                  <template v-slot:activator="{ on }">
                    <v-icon
                      @click="openSelectSupplier(child)"
                      v-on="on"
                      class="ml-2 bold-icon pointer float-right"
                      color="#79839B"
                    >
                      mdi-magnify
                    </v-icon>
                  </template>
                  <span>Select Supplier</span>
                </v-tooltip>
              </v-card>
            </template>
            <template v-else-if="header.value === 'qty'">
              <div :class="{ 'no-content rounded-1': !child[header.value] }">
                <v-edit-dialog :return-value.sync="child[header.value]">
                  <div class="text">
                    {{ child[header.value] }}
                  </div>
                  <template v-slot:input>
                    <v-text-field v-model="child[header.value]"></v-text-field>
                  </template>
                </v-edit-dialog>
              </div>
            </template>
            <template v-else-if="header.value === 'action'">
              <div @click.stop class="action">
                <v-icon
                  @click="deleteItem(item, child)"
                  class="pointer"
                  color="#79839B"
                  >mdi-minus-circle</v-icon
                >
              </div>
            </template>
            <template v-else>
              <div :class="{ 'no-content rounded-1': !child[header.value] }">
                <v-edit-dialog
                  :return-value.sync="child[header.value]"
                  :large="!errors.first(header.value)"
                >
                  <div class="text">
                    {{ child[header.value] }}
                  </div>
                  <template v-slot:input>
                    <v-text-field
                      v-model="child[header.value]"
                      v-validate="'usd'"
                      :name="header.value"
                    ></v-text-field>
                    <span class="vee-validate-error">{{
                      errors.first(header.value)
                    }}</span>
                  </template>
                </v-edit-dialog>
              </div>
            </template>
          </td>
        </tr>
      </template>
    </v-data-table>
    <Select
      @select="select"
      :show.sync="showSelect"
      :show-save="false"
      :title="selectTitle"
      :headers="selectHeaders"
      :items="selectItems"
      :loading="selectLoading"
      width="904"
    ></Select>
  </div>
</template>
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { isValidKey } from "@/common/constants/Utils";
import Select from "@/components/Quotation/Dialog/Select/Select.vue";
import { IItems, IItemsChild } from "@/components/Quotation/index";
interface ISelectItem {
  id: string;
  itemNumber: string;
  serialNumber: string;
  itemDescription: string;
  unitCost: string;
}
interface ISelectSupplier {
  itemNumber: string;
  name: string;
}
interface ISelectHeader {
  text: string;
  value: string;
}
@Component({
  components: {
    Select,
  },
  props: {
    items: {
      type: Array,
      default: () => [],
    },
  },
})
export default class Items extends Vue {
  // Table
  selectedItem: IItemsChild | null = null;
  tableHeaders = [
    {
      text: "Line #",
      value: "line",
      width: "90",
    },
    {
      text: "Description",
      value: "description",
    },
    {
      text: "Supplier",
      value: "supplier",
    },
    {
      text: "Unit Cost",
      value: "unitCost",
    },
    {
      text: "Unit Rate",
      value: "unitRate",
    },
    {
      text: "Qty",
      value: "qty",
    },
    {
      text: "Tot. Cost",
      value: "totalCost",
    },
    {
      text: "Tot. Amt",
      value: "totalAmt",
    },
    {
      text: "G.P.",
      value: "gain",
    },
    {
      text: "GP%",
      value: "gp",
    },
    {
      text: "",
      value: "action",
    },
  ];
  get propItems() {
    return this.$props.items;
  }
  arrObjSum(arr: IItemsChild[], key: string) {
    let sum: number | string = arr.reduce((previousValue: number, item) => {
      if (isValidKey(key, item)) {
        return (
          previousValue + Number((item[key] as string).split(",").join(""))
        );
      } else {
        return previousValue;
      }
    }, 0);
    sum = sum.toLocaleString();
    if (!this.ifFloat(sum)) {
      sum = sum += ".00";
    }
    return sum;
  }
  arrObjAverage(arr: IItemsChild[], key: string) {
    if (arr.length === 0) {
      return "0.00%";
    }
    let sum: number = arr.reduce((previousValue: number, item) => {
      if (isValidKey(key, item)) {
        return (
          previousValue + Number((item[key] as string).split("%").join(""))
        );
      } else {
        return previousValue;
      }
    }, 0);

    const average = (sum / arr.length).toFixed(2) + "%";
    return average;
  }
  ifFloat(num: number | string) {
    if (typeof num === "number") {
      return String(num).split(".").length > 1;
    } else if (typeof num === "string") {
      return num.split(".").length > 1;
    } else {
      return false;
    }
  }
  createItemChild(): IItemsChild {
    return {
      id: "",
      line: "",
      description: "",
      supplier: "",
      unitCost: "",
      unitRate: "",
      qty: "",
      totalCost: "",
      totalAmt: "",
      gain: "",
      gp: "",
    };
  }
  addItem(items: IItems) {
    const itemChild = this.createItemChild();
    itemChild.id = String(new Date().getTime());
    itemChild.line = (
      Number(items.line) +
      (items.children.length + 1) / 100
    ).toFixed(2);
    items.children.push(itemChild);
  }

  // Select
  // 1.select item 2.select supplier
  step = -1;
  showSelect = false;
  selectLoading = false;
  selectHeaders: ISelectHeader[] = [];
  selectItems: object[] = [];
  selectTitle = "";
  openSelect() {
    this.showSelect = true;
  }
  closeSelect() {
    this.showSelect = false;
  }
  select(item: ISelectItem | ISelectSupplier) {
    if (this.step === 1) {
      this.selectItem(item as ISelectItem);
    } else if (this.step === 2) {
      this.selectSupplier(item as ISelectSupplier);
    }
    this.closeSelect();
  }
  // add item
  addItemHeaders = [
    {
      text: "Item Number",
      value: "itemNumber",
    },
    {
      text: "Serial Number",
      value: "serialNumber",
    },
    {
      text: "Item Description",
      value: "itemDescription",
    },
    {
      text: "Unit Cost",
      value: "unitCost",
    },
  ];
  openSelectItem(item: IItemsChild) {
    this.selectHeaders = this.addItemHeaders;
    this.step = 1;
    this.selectedItem = item;
    this.selectTitle = "Add Item";
    this.getSelectItems();
    this.openSelect();
  }
  selectItem(item: ISelectItem) {
    if (this.selectedItem) {
      this.selectedItem.description = item.itemDescription;
    }
  }
  getSelectItems() {
    this.selectItems = [];
    this.selectLoading = true;
    setTimeout(() => {
      this.selectItems = [
        {
          id: "1",
          itemNumber: "Items 1",
          serialNumber: "2368882030",
          itemDescription: "modern style luxury light",
          unitCost: "65,000.00",
        },
        {
          id: "2",
          itemNumber: "Items 2",
          serialNumber: "2382999377",
          itemDescription: "huge crystal LED",
          unitCost: "90,000.00",
        },
        {
          id: "3",
          itemNumber: "Items 3",
          serialNumber: "2382999333",
          itemDescription: "Golen crystal chandelier",
          unitCost: "95,000.00",
        },
      ];
      this.selectLoading = false;
    }, 1000);
  }
  // select supplier
  selectSupplierHeaders = [
    {
      text: "Item Number",
      value: "itemNumber",
    },
    {
      text: "Name",
      value: "name",
    },
  ];

  openSelectSupplier(item: IItemsChild) {
    this.selectHeaders = this.selectSupplierHeaders;
    this.step = 2;
    this.selectedItem = item;
    this.selectTitle = "Select Supplier";
    this.getSelectSupplierItems();
    this.openSelect();
  }

  getSelectSupplierItems() {
    this.selectItems = [];
    this.selectLoading = true;
    setTimeout(() => {
      this.selectItems = [
        {
          itemNumber: "SU-22010",
          name: "Advance Tech",
        },
        {
          itemNumber: "SU-22011",
          name: "Wing Kee",
        },
      ];
      this.selectLoading = false;
    }, 2000);
  }

  selectSupplier(item: ISelectSupplier) {
    if (this.selectedItem) {
      this.selectedItem.supplier = item.name;
    }
  }

  // action
  deleteItem(parent: IItems, child: IItemsChild) {
    const index = parent.children.indexOf(child);
    parent.children.splice(index, 1);
  }
}
</script>
<style lang="scss" scoped>
@import "./Items.scss";
</style>
